/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package py.com.davweb.popup;

import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.Calendar;
import com.sun.webui.jsf.component.DropDown;
import com.sun.webui.jsf.component.TextField;
import com.sun.webui.jsf.model.Option;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.event.ValueChangeEvent;
import org.hibernate.Session;
import org.hibernate.Transaction;
import py.com.davweb.RequestBean1;
import py.com.davweb.ApplicationBean1;
import py.com.davweb.SessionBean1;
import py.com.domain.Ciudades;
import py.com.domain.Paises;
import py.com.domain.Personas;
import py.com.domain.Profesiones;
import py.com.webdav.util.HibernateUtil;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version PersonaPopUp.java
 * @version Created on Apr 27, 2010, 5:14:13 PM
 * @author markos
 */
public class PersonaPopUp extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private TextField txtFiltro = new TextField();

    public TextField getTxtFiltro() {
        return txtFiltro;
    }

    public void setTxtFiltro(TextField tf) {
        this.txtFiltro = tf;
    }
    private TextField txtNombreApellido = new TextField();

    public TextField getTxtNombreApellido() {
        return txtNombreApellido;
    }

    public void setTxtNombreApellido(TextField tf) {
        this.txtNombreApellido = tf;
    }
    private TextField txtDireccion = new TextField();

    public TextField getTxtDireccion() {
        return txtDireccion;
    }

    public void setTxtDireccion(TextField tf) {
        this.txtDireccion = tf;
    }
    private TextField txtCI = new TextField();

    public TextField getTxtCI() {
        return txtCI;
    }

    public void setTxtCI(TextField tf) {
        this.txtCI = tf;
    }
    private Calendar calendar = new Calendar();

    public Calendar getCalendar() {
        return calendar;
    }

    public void setCalendar(Calendar c) {
        this.calendar = c;
    }
    private TextField txtTelefono = new TextField();

    public TextField getTxtTelefono() {
        return txtTelefono;
    }

    public void setTxtTelefono(TextField tf) {
        this.txtTelefono = tf;
    }
    private DropDown dropEstadoCivil = new DropDown();

    public DropDown getDropEstadoCivil() {
        return dropEstadoCivil;
    }

    public void setDropEstadoCivil(DropDown dd) {
        this.dropEstadoCivil = dd;
    }
    private DropDown dropPais = new DropDown();

    public DropDown getDropPais() {
        return dropPais;
    }

    public void setDropPais(DropDown dd) {
        this.dropPais = dd;
    }
    private DropDown dropNacionalidad = new DropDown();
    private Option[] listaSexo = {new Option("M", "Masculino"), new Option("F", "Femenino")};
    private Option[] listaEstadoCivil = {new Option("C", "Casado/a"), new Option("S", "Soltero/a"), new Option("D", "Divorciado/a")};
    private List<Option> listaCiudadesOption;
    private List<Option> listaPaisOption;
    private List<Option> listaNacionalidadOption;
    private List<Option> listaProfesionOption;

    public List<Option> getListaCiudadesOption() {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = s.beginTransaction();
        listaCiudadesOption = new ArrayList<Option>();
        try {
            List<Ciudades> l = s.createQuery("from Ciudades").list();
            for (Ciudades c : l) {
                listaCiudadesOption.add(new Option(c.getCiCiudad().toString(), c.getCiDescripcion()));
            }
            t.commit();
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
        }
        return listaCiudadesOption;
    }

    public void setListaCiudadesOption(List<Option> listaCiudadesOption) {
        this.listaCiudadesOption = listaCiudadesOption;
    }

    public Option[] getListaEstadoCivil() {
        return listaEstadoCivil;
    }

    public void setListaEstadoCivil(Option[] listaEstadoCivil) {
        this.listaEstadoCivil = listaEstadoCivil;
    }

    public List<Option> getListaNacionalidadOption() {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = s.beginTransaction();
        listaNacionalidadOption = new ArrayList<Option>();
        try {
            List<Paises> l = s.createQuery("from Paises").list();
            for (Paises p : l) {
                listaNacionalidadOption.add(new Option(p.getPaPais().toString(), p.getPaDescripcion()));
            }
            t.commit();
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
        }
        return listaNacionalidadOption;
    }

    public void setListaNacionalidadOption(List<Option> listaNacionalidadOption) {
        this.listaNacionalidadOption = listaNacionalidadOption;
    }

    public List<Option> getListaPaisOption() {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = s.beginTransaction();
        listaPaisOption = new ArrayList<Option>();
        try {
            List<Paises> l = s.createQuery("from Paises").list();
            for (Paises p : l) {
                listaPaisOption.add(new Option(p.getPaPais().toString(), p.getPaDescripcion()));
            }
            t.commit();
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
        }
        return listaPaisOption;
    }

    public void setListaPaisOption(List<Option> listaPaisOption) {
        this.listaPaisOption = listaPaisOption;
    }

    public List<Option> getListaProfesionOption() {
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = s.beginTransaction();
        listaProfesionOption = new ArrayList<Option>();
        try {
            List<Profesiones> l = s.createQuery("from Profesiones").list();
            for (Profesiones p : l) {
                listaProfesionOption.add(new Option(p.getPrProfesion().toString(), p.getPrDescripcion()));
            }
            t.commit();
        } catch (Exception e) {
            t.rollback();
            e.printStackTrace();
        }
        return listaProfesionOption;
    }

    public void setListaProfesionOption(List<Option> listaProfesionOption) {
        this.listaProfesionOption = listaProfesionOption;
    }

    public Option[] getListaSexo() {
        return listaSexo;
    }

    public void setListaSexo(Option[] listaSexo) {
        this.listaSexo = listaSexo;
    }

    public DropDown getDropNacionalidad() {
        return dropNacionalidad;
    }

    public void setDropNacionalidad(DropDown dd) {
        this.dropNacionalidad = dd;
    }
    private DropDown dropProfesion = new DropDown();

    public DropDown getDropProfesion() {
        return dropProfesion;
    }

    public void setDropProfesion(DropDown dd) {
        this.dropProfesion = dd;
    }
    private DropDown dropSexo = new DropDown();

    public DropDown getDropSexo() {
        return dropSexo;
    }

    public void setDropSexo(DropDown dd) {
        this.dropSexo = dd;
    }
    private DropDown dropLugar = new DropDown();

    public DropDown getDropLugar() {
        return dropLugar;
    }

    public void setDropLugar(DropDown dd) {
        this.dropLugar = dd;
    }
    private DropDown dropFiltro = new DropDown();

    public DropDown getDropFiltro() {
        return dropFiltro;
    }

    public void setDropFiltro(DropDown dd) {
        this.dropFiltro = dd;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public PersonaPopUp() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("PersonaPopUp Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
        btnBuscar_action();
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }
    private List<Personas> listaPersonas;
    private String where;

    public List<Personas> getListaPersonas() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tran = session.beginTransaction();
        listaPersonas = new ArrayList<Personas>();
        try {
            listaPersonas = session.createQuery("from Personas " + where).list();
            tran.commit();
        } catch (Exception e) {
            tran.rollback();
            e.printStackTrace();
        }
        return listaPersonas;
    }

    public void setListaPersonas(List<Personas> listaPersonas) {
        this.listaPersonas = listaPersonas;
    }

    public String btnBuscar_action() {
        listaPersonas = new ArrayList<Personas>();
        try {
            where = "";

            if (txtFiltro.getText() != null && !txtFiltro.getText().toString().equals("")) {
                if (dropFiltro.getSelected().toString().equals("nombre")) {
                    where = " where upper(dnApellidoNombre) like '" + txtFiltro.getText().toString().toUpperCase() + "%'";
                } else if (dropFiltro.getSelected().toString().equals("code")) {
                    where = " where dnPersona = " + txtFiltro.getText().toString().trim();
                }
            }
            getListaPersonas();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String botonLimpiar_action() {
        txtFiltro.setText("");
        return null;
    }

    public String btnOk_action() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tran = session.beginTransaction();
        try {
            Personas p = new Personas();
            p.setDnApellidoNombre(txtNombreApellido.getText().toString());
            if (txtCI.getText() != null) {
                p.setDnCedula(Integer.parseInt(txtCI.getText().toString()));
            }
            if (txtDireccion.getText() != null) {
                p.setDnDireccion(txtDireccion.getText().toString());
            }
            if (dropEstadoCivil.getSelected() != null) {
                p.setDnEstadoCivil(dropEstadoCivil.getSelected().toString());
            }
            if (calendar.getSelectedDate() != null) {
                p.setDnFechaNacimiento(calendar.getSelectedDate());
            }
            p.setDnLugarNacimiento((Ciudades) session.load(Ciudades.class, Integer.parseInt(dropLugar.getSelected().toString())));
            p.setDnNacionalidad((Paises) session.load(Paises.class, Integer.parseInt(dropNacionalidad.getSelected().toString())));
            p.setDnPaisOrigen((Paises) session.load(Paises.class, Integer.parseInt(dropPais.getSelected().toString())));
            p.setDnProfesion((Profesiones) session.load(Profesiones.class, Integer.parseInt(dropProfesion.getSelected().toString())));
            p.setDnSexo(dropSexo.getSelected().toString().toCharArray()[0]);
            if (txtTelefono.getText() != null) {
                p.setDnTelefono(txtTelefono.getText().toString());
            }
            if (getSessionBean1().getPersona() == null) {
                session.save(p);
            } else {
                session.merge(p);
            }
            tran.commit();
            getSessionBean1().setPersona(null);
            return "success";
        } catch (Exception e) {
            getSessionBean1().setPersona(null);
            tran.rollback();
            e.printStackTrace();
            return "persona_fail";
        }
    }

    public String btnCancel_action() {
        return "persona_cancel";
    }
    private Option[] listaOpciones = {new Option("code", "Codigo"), new Option("nombre", "Nombre")};

    public Option[] getListaOpciones() {
        return listaOpciones;
    }

    public void setListaOpciones(Option[] listaOpciones) {
        this.listaOpciones = listaOpciones;
    }

    public void calendar_processValueChange(ValueChangeEvent event) {
        long fechaActual = System.currentTimeMillis();
        Date edad = new Date(fechaActual);
        java.util.Calendar cNacimiento = java.util.Calendar.getInstance();
        java.util.Calendar cActual = java.util.Calendar.getInstance();

        cNacimiento.setTime(calendar.getSelectedDate());
        cActual.setTime(edad);
    }

    public void dropPais_processValueChange(ValueChangeEvent event) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tran = session.beginTransaction();
        try {
            tran.begin();
            List<Ciudades> lCiudad = session.createQuery(" from Ciudades where ciDepartamento.dpRegion.rgPais.paPais = " + dropPais.getSelected().toString()).list();
            listaCiudadesOption = new ArrayList<Option>();
            for (Ciudades c : lCiudad) {
                listaCiudadesOption.add(new Option(c.getCiCiudad().toString(), c.getCiDescripcion()));
            }
            tran.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tran.rollback();
        }
    }
}

